package com.example.shiwu.fragment;

import static androidx.constraintlayout.motion.utils.Oscillator.TAG;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.example.shiwu.R;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.vo.MyQueue;
import com.example.shiwu.model.MainInfo;
import com.example.shiwu.service.DeviceService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.util.ByteUtil;
import com.example.shiwu.util.ContextVariable;
import com.example.shiwu.util.DataParseUtil;
import com.example.shiwu.view.MainInfoView;

import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class MainInfoBackFragment extends Fragment {
    private String content;
    private SocketConnectThread mConnectThread;
    private SocketReceiveThread mReceiveThread;
    private MainInfoView mainInfoView;
    private final int STATE_DISCONNECTED = 1;
    private final int STATE_CONNECTING = 2;
    private final int STATE_CONNECTED = 3;
    private int mSocketConnectState = STATE_DISCONNECTED;
    private static final int MSG_TIME_SEND = 1;
    private static final int MSG_SOCKET_CONNECT = 2;
    private static final int MSG_SOCKET_DISCONNECT = 3;
    private static final int MSG_SOCKET_CONNECTFAIL = 4;
    private static final int MSG_RECEIVE_DATA = 5;
    private static final int MSG_SEND_DATA = 6;
    public Socket mSocket;

    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor editor;
    private final int DEFAULT_PORT = 8086;
    private int mClientPort = 8080; //端口,默认为8086，可以进行设置
    private OutputStream mOutStream;
    private InputStream mInStream;
    private Handler mSubThreadHandler;
    private HandlerThread mHandlerThread;
    private TextView edition;
    private View view;
    private int success_count = 0;
    private Boolean bool = true;
    private ArrayList<String> msgArray;
    private MyQueue queue;
    private DataParseUtil dataParseUtil;
    private DeviceService deviceService;
    private ItemsService itemsService;
    private String itemsId;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TIME_SEND:
                    break;
                case MSG_SOCKET_CONNECT:
                    mSocketConnectState = STATE_CONNECTED;
                    System.out.println(R.string.disconnect);
                    mReceiveThread = new SocketReceiveThread();
                    mReceiveThread.start();
                    break;
                case MSG_SOCKET_DISCONNECT:
                    System.out.println(R.string.connect);
                    mSocketConnectState = STATE_DISCONNECTED;
                    closeConnection();
                    break;
                case MSG_SOCKET_CONNECTFAIL:
                    mSocketConnectState = STATE_DISCONNECTED;
                    System.out.println("======================连接失败=========================");
                    mReceiveThread = new SocketReceiveThread();
                    mReceiveThread.start();
                    break;
                case MSG_RECEIVE_DATA:
                    MainInfo mainInfo = new MainInfo();
                    ArrayList msglis = (ArrayList) msg.obj;
                    mainInfo.setFirmwareeDition(msglis.get(0).toString());
                    mainInfo.setPowerSource(msglis.get(1).toString());
                    mainInfo.setChannel(msglis.get(2).toString());
                    mainInfo.setVoltage(msglis.get(3).toString());
                    mainInfo.setTemp(msglis.get(4).toString());
                    mainInfo.setIntemp(msglis.get(5).toString());
                    initView(mainInfo);
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_maininfo, container, false);
        //initView(null);
        //edition = view.findViewById(R.id.maininfo_firmwaree_dition_val);
        msgArray = new ArrayList<String>();
        dataParseUtil = new DataParseUtil();
        deviceService = new DeviceService();
        Items items = findSelectItem();

        itemsId = items.getId().toString();
        closeConnection();
        initHandlerThraed();//启动socket

        startConnect();
        queue = new MyQueue();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeConnection();
    }
    private Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            items1 = lis.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return items1;
    }

    public void initView(MainInfo mainInfo) {
        mainInfoView = new MainInfoView((Activity) this.getContext(), R.layout.activity_maininfo, view);
        mainInfoView.createView();
        if (mainInfo != null) {
            mainInfoView.bindView(mainInfo);
        }
    }


    public void closeConnection() {
        if (mReceiveThread != null) {
            mReceiveThread.threadExit = true;
            mReceiveThread = null;
        }
        if(mConnectThread!= null){
            mConnectThread = null;
        }

        if (mOutStream != null) {
            try {
                mOutStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
            mOutStream = null;
        }
        if (mInStream != null) {
            try {
                mInStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mInStream = null;
        }

        if (mSocket != null) {
            try {
                mSocket.close();

            } catch (IOException e) {
            }
            mSocket = null;
        }
        System.out.println("--------关闭SOCKET---------");
        //mSocketConnectState = STATE_DISCONNECTED;
    }

    private void sendTxt(String str) {
        if (mSocket == null) {
            System.out.println("================================ socket没有连接 ===============================");
            return;
        }

        if (str.length() == 0)
            return;
        Message msg = new Message();
        msg.what = MSG_SEND_DATA;
        msg.obj = str;
        mSubThreadHandler.sendMessage(msg);
    }

    private void startConnect() {
        Log.i(TAG, "startConnect");
        if (ContextVariable.IP == null || ContextVariable.IP.length() == 0) {
            System.out.println("============================== 请设置socket ip地址 =======================");
            return;
        }
        if (mSocketConnectState != STATE_DISCONNECTED) return;
        mConnectThread= null;
        mConnectThread = new SocketConnectThread();
        mConnectThread.start();
        mSocketConnectState = STATE_CONNECTING;
        System.out.println(R.string.state_connecting);
    }

    class SocketReceiveThread extends Thread {
        private boolean threadExit;
        private int blen=1024;

        public SocketReceiveThread() {
            threadExit = false;
        }

        public void run() {
            byte[] buffer = new byte[blen];
            Log.i(TAG, "read read runrunrunrunrunrunrunrunrunrunrunrunrunrunrun");
            while (threadExit == false) {
                try {
                    //读取数据，返回值表示读到的数据长度。-1表示结束
                    int count = mInStream.read(buffer);
                    if (count == -1) {
                        Log.i(TAG, "read read -1");
                        mHandler.sendEmptyMessage(MSG_SOCKET_DISCONNECT);
                        break;
                    } else {
                        String receiveData = new String(buffer, 0, count);
                        Log.i(TAG, "==========read buffer:" + receiveData + ",count=" + count);
                        //Log.i(TAG, "==========read buffer1111:" + buffer );

                        String msgCode = receiveData.substring(2, receiveData.indexOf(";"));
                        if (msgCode.equals("Success")) {
                            success_count += 1;
                            if(success_count == 2){
                                sendTxt("18,get;13,update;");
                            }
                        }else {
                            int semicolon_inx = ByteUtil.bByteForSemicolon(buffer,0);
                            byte[] byte_18 = ByteUtil.subByte(buffer,0,semicolon_inx);
                            byte[] byte_14 = ByteUtil.subByte(buffer,semicolon_inx+4,count-semicolon_inx-4);
                            for (byte b :byte_14) {
                                queue.enQueue(b);
                            }
                            String msglis_18 = ByteUtil.byteTransformAscil(byte_18);
                            //System.out.println("  msglis_18 ===================="+ msglis_18);
                            String mas_18_val = msglis_18.split(",")[1];//固件版本

                            Double batt_vol = Double.valueOf(receive_one_field());//电源
                            System.out.println("  电源电压 ===================="+ batt_vol);
                            String tx_high_vol = receive_one_field();//高压

                            String temperature1 = receive_one_field();//温度
                            String temperature = temperature1.substring(0,temperature1.indexOf("."))+"°C";//温度
                            String humidity1 = receive_one_field();//湿度
                            String humidity = humidity1.substring(0,humidity1.indexOf("."))+"°C";//湿度

                            int batt_vol_int = batt_vol.intValue();
                            BigDecimal a = new BigDecimal(batt_vol_int);
                            BigDecimal b = new BigDecimal(ContextVariable.power_supply);
                            BigDecimal c = a.divide(b,2,BigDecimal.ROUND_HALF_DOWN);
//                            System.out.println(c);
                            String batt_percent = String.valueOf(c.multiply(new BigDecimal(100)));
                            String batt_percent_val = batt_percent.substring(0,batt_percent.indexOf("."))+"%";
//                            System.out.println(batt_percent_val);
                            msgArray.add(mas_18_val);
                            msgArray.add(batt_percent_val);
                            msgArray.add(ContextVariable.channel);
                            msgArray.add(tx_high_vol);
                            msgArray.add(temperature);
                            msgArray.add(humidity);
                            if (success_count == 2) {

                                Message msg = new Message();
                                msg.what = MSG_RECEIVE_DATA;
                                msg.obj = msgArray;
                                mHandler.sendMessage(msg);
                            }
                            Device device = new Device();
                            device.setItemId(itemsId);
                            device.setSn(mas_18_val);
                            deviceService.saveOrUpdata(device);
                        }
                    }
                } catch (IOException e) {
                    System.out.println("+++++++++++++++ receive +++++++++++++++");
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        void threadExit() {
            threadExit = true;
        }
    }



    private synchronized String receive_one_field() throws InterruptedException, UnsupportedEncodingException {
        Boolean escaped = false;
        Boolean command_sep_found = false;
        ArrayList<Byte> one_field = new ArrayList<Byte>();
        Boolean bl = true;
        String msgbt ="";
        while (bl) {

            byte tmp = (byte) queue.deQueue();
            if (escaped) {
                if (tmp == 44 || tmp == 59 || tmp == 47) {
                    one_field.add(tmp);
                    escaped = false;
                } else {
                    one_field.add(tmp);
                    escaped = false;
                }
            } else {
                if (tmp == 47) {
                    //遇到 / 就escaped = True 继续循环
                    escaped = true;
                } else if (tmp == 44) {
                    break;
                } else if (tmp == 59) {
                    command_sep_found = true;
                    break;
                } else {
                    one_field.add(tmp);
                }
            }

        }
        if(one_field.size()>0){
            msgbt = recv_float(one_field);
        }

        return msgbt;
    }
    private String recv_float(ArrayList<Byte> val) {
        List<Byte> ab5 = dataParseUtil.objToByList(val);
        byte[] str_one_field5 = dataParseUtil.listTobyte(ab5);
        return dataParseUtil.recv_float(str_one_field5);
    }

    class SocketConnectThread extends Thread {
        @Override
        public void run() {
            try {
                //连接服务端，指定服务端ip地址和端口号。
                mSocket = null;
                mSocket = new Socket(ContextVariable.IP, mClientPort);
                //mSocket.setSoTimeout(1000);
                // 判断客户端和服务器是否连接成功
                System.out.println(mSocket.isConnected());
                if (mSocket != null) {
                    //获取输出流、输入流
                    mOutStream = mSocket.getOutputStream();
                    mInStream = mSocket.getInputStream();
                    if (success_count == 0) {
                        sendTxt("22,M;");
                        Thread.sleep(1000);
                        success_count = 0;
                        sendTxt("22,M;");
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
                mHandler.sendEmptyMessage(MSG_SOCKET_CONNECTFAIL);
                return;
            }
            Log.i(TAG, "============================== connect success =====================");
            mHandler.sendEmptyMessage(MSG_SOCKET_CONNECT);
        }

    }

    private void initHandlerThraed() {
        //创建HandlerThread实例
        mHandlerThread = new HandlerThread("handler_thread");
        //开始运行线程
        mHandlerThread.start();
        //获取HandlerThread线程中的Looper实例
        Looper loop = mHandlerThread.getLooper();
        //创建Handler与该线程绑定。
        mSubThreadHandler = new Handler(loop) {
            public void handleMessage(Message msg) {
                Log.i(TAG, "mSubThreadHandler handleMessage thread:" + Thread.currentThread());
                switch (msg.what) {
                    case MSG_SEND_DATA:
                        writeMsg((String) msg.obj);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    private void writeMsg(String msg) {
        Log.i(TAG, "writeMsg msg=" + msg);
        if (msg.length() == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg.getBytes());//发送
            mOutStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
